using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using EntLibEC.Cmn;
using EntLibEC.Biz.Report;
using EntLibEC.Biz;

namespace EntLibEC.View.Report
{
	/// <summary>
	/// Summary description for SaleReportByCategory.
	/// </summary>
	public partial class SaleReportByCategory : PageBase
	{
		private int quantitySum = 0;
		private decimal costSum = 0;
		private decimal amountSum = 0;
		private decimal rateTotal = -1;
	
		protected void Page_Load(object sender, System.EventArgs e)
		{
			base.CheckAccess((int)AppEnum.Privilege.SaleReportSearch,true ,null);
			if ( !Page.IsPostBack )
			{				
				txtDateFrom.Text = DateTime.Now.ToString(AppConst.DateFormat).Substring(0,7) + "-01";
				txtDateTo.Text = DateTime.Now.ToString(AppConst.DateFormat);
				ucCategory.BindCategory();
                ucProductType.BindProductType(true);

				btnExport.Enabled = false;
			}
			txtDateFrom.Attributes["onclick"]= "javascript:calendar()";
			txtDateTo.Attributes["onclick"]= "javascript:calendar()";
		}

		private bool checkForm()
		{
			if ( !checkDate(txtDateFrom, "Date From") || !checkDate(txtDateTo, "Date To"))
				return false;

			return true;

		}
		private bool checkDate(TextBox txt, string txtName)
		{
			if ( txt.Text.Trim() == "")
			{
				Assert(lblMessage, txtName + " can't be empty", -1);
				return false;
			}
			else
			{
				try
				{
					Convert.ToDateTime(txt.Text.Trim());
				}
				catch
				{
					Assert(lblMessage, txtName + " format error", -1);
					return false;
				}
			}
			return true;

		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.dgResult.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgResult_ItemDataBound);

		}
		#endregion

		protected void btnSearch_Click(object sender, System.EventArgs e)
		{
			if (!checkForm())
			    return;
			 Hashtable ht =new Hashtable(5);

			ht.Add("DateFrom" , txtDateFrom.Text.Trim()); 
			ht.Add("DateTo" , txtDateTo.Text.Trim());

			if (ddlCategory.SelectedValue == "First")
			{
				ht.Add("Category" , "C1Name");
			}
			else if (ddlCategory.SelectedValue == "Second")
			{
				ht.Add("Category" , "C2Name");
				if (ucCategory.C1SysNo != AppConst.IntNull)
					ht.Add("CategorySysNo" , " c1sysno = " + ucCategory.C1SysNo);
			}
			else if (ddlCategory.SelectedValue == "Third")
			{
			    ht.Add("Category" , "C3Name");
				if (ucCategory.C2SysNo != AppConst.IntNull)
					ht.Add("CategorySysNo" , " c2sysno = " + ucCategory.C2SysNo);
				else if (ucCategory.C1SysNo != AppConst.IntNull)
					ht.Add("CategorySysNo" , " c1sysno = " + ucCategory.C1SysNo);
			}

			if (ddlSalesType.SelectedValue != "All")
			{
			   ht.Add("IsWholeSale" , int.Parse(ddlSalesType.SelectedValue));
			}

            if (ucProductType.ProductTypeSysNo != AppConst.IntNull)
                ht.Add("ProductType", ucProductType.ProductTypeSysNo);

			ht.Add("OrderBy" , ddlOrderBy.SelectedValue.ToString().Trim());

			DataSet ds = ReportManager.GetInstance().GetSaleReportByCategory(ht);
			dgResult.DataSource = convertDs(ds);
			dgResult.DataBind();

			int rows = 0;
			if ( Util.HasMoreRow(ds) )
			{
				rows = ds.Tables[0].Rows.Count;
				btnExport.Enabled = true;
			}
			Assert(lblMessage, rows.ToString() + " record(s)", 1);
	   }

		private DataSet convertDs(DataSet ds)
		{
		    if (!Util.HasMoreRow(ds))
			   return ds;
			
			ds.Tables[0].Columns.Add("TotalCostCvt");
			ds.Tables[0].Columns.Add("TotalAmountCvt");
			ds.Tables[0].Columns.Add("ProfitCvt");

			foreach( DataRow dr in ds.Tables[0].Rows )
			{			   
 
				costSum += Util.TrimDecimalNull(dr["TotalCost"]);
				amountSum += Util.TrimDecimalNull(dr["TotalAmount"]);
                quantitySum += Util.TrimIntNull(dr["TotalQuantity"]);

				decimal totalCost = Util.TrimDecimalNull(dr["TotalCost"]);
				decimal totalAmount = Util.TrimDecimalNull(dr["TotalAmount"]);

				dr["TotalCostCvt"] = (totalCost/1.17m).ToString(AppConst.DecimalFormatWithGroup);
				dr["TotalAmountCvt"] = (totalAmount/1.17m).ToString(AppConst.DecimalFormatWithGroup);

				decimal rate = -1;
				if ( totalAmount != 0)
					rate = (totalAmount - totalCost)/totalAmount;
				dr["ProfitCvt"] = (rate * 100).ToString(AppConst.DecimalFormat) + "%";
			}

			return ds ;

		}

		private string ToFooterString(int x)
		{
			if ( x == 0)
				return "";
			return x.ToString(AppConst.IntFormatWithGroup);
		}
		private string ToFooterString(decimal x)
		{
			if ( x == 0)
				return "";
			return x.ToString(AppConst.DecimalFormatWithGroup);
		}

		private void dgResult_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			if(e.Item.ItemType == ListItemType.Footer)
			{
				e.Item.Cells[1].Text = ToFooterString(quantitySum);
				e.Item.Cells[2].Text = ToFooterString(costSum/1.17m);
				e.Item.Cells[3].Text = ToFooterString(amountSum/1.17m);
				
                if (amountSum != 0)
				    rateTotal = (amountSum - costSum) / amountSum;
				e.Item.Cells[4].Text = (rateTotal * 100).ToString(AppConst.DecimalFormat) + "%";

			}
		
		}

		protected void btnExport_Click(object sender, System.EventArgs e)
		{
			Util.ToExcel(dgResult, "Sale Report By Category", "");
		}

	}
}
